<template>
    <van-form
      style="margin-bottom: 24px"
      ref="formInstance"
      validate-trigger="onSubmit"
    >
      <BaseInput
        v-for="item of fields"
        :label="item.label"
        v-model:value="form[item.key]"
        v-bind="item.props"
      ></BaseInput>
    </van-form>
    <slot></slot>
  </template>
  
  <script setup lang="ts">
  import { reactive, PropType, ref } from "vue";
  import BaseInput from "./BaseInput.vue";
  import type { FieldProps, FormInstance } from "vant";
  defineProps({
    fields: {
      type: Array as PropType<
        Array<{ label: string; key: string; props: Partial<FieldProps> }>
      >,
    },
  });
  const form = reactive<Record<string, any>>({}),
    formInstance = ref<FormInstance | null>(null);
  const onSubmit = async () => {
    try {
      await formInstance.value?.validate();
      return Promise.resolve(form);
    } catch {
      setTimeout(() => {
        formInstance.value?.resetValidation();
      }, 2000);
      return Promise.reject();
    }
  };
  defineExpose({
    form,
    onSubmit,
  });
  </script>
  
  <style scoped></style>